<template>
  <div class="user-management">
    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧部门树 -->
      <div class="department-panel">
        <div class="panel-header">
          <div class="header-title-section">
            <h3>组织架构</h3>
          </div>
          <div class="search-box">
            <el-input
              v-model="departmentSearchKeyword"
              placeholder="搜索部门..."
              size="small"
              clearable
              prefix-icon="Search"
            />
          </div>
        </div>
        <div class="department-tree">
          <el-tree
            ref="departmentTreeRef"
            :data="filteredDepartmentTree"
            :props="treeProps"
            :expand-on-click-node="false"
            :highlight-current="true"
            node-key="id"
            @node-click="handleDepartmentClick"
            @node-contextmenu="handleDepartmentRightClick"
          >
            <template #default="{ node, data }">
              <div class="tree-node">
                <el-icon class="node-icon">
                  <OfficeBuilding v-if="data.type === 'company'" />
                  <User v-else />
                </el-icon>
                <span class="node-label">{{ data.name }}</span>
                <span class="user-count">({{ data.userCount || 0 }}人)</span>
              </div>
            </template>
          </el-tree>
        </div>
      </div>
      <!-- 右侧用户列表 -->
      <div class="user-panel">
        <div class="panel-header">
          <!-- 搜索和筛选区域 -->
          <div class="search-section">
            <div class="search-filters">
              <el-input
                v-model="userSearchKeyword"
                placeholder="搜索用户..."
                size="small"
                clearable
                prefix-icon="Search"
                style="width: 200px;"
              />
              <el-select
                v-model="roleFilter"
                placeholder="角色筛选"
                size="small"
                clearable
                style="width: 120px;"
              >
                <el-option label="管理员" value="admin" />
                <el-option label="后台人员" value="staff" />
                <el-option label="普通用户" value="user" />
              </el-select>
              <el-select
                v-model="statusFilter"
                placeholder="状态筛选"
                size="small"
                clearable
                style="width: 120px;"
              >
                <el-option label="启用" value="active" />
                <el-option label="禁用" value="inactive" />
              </el-select>
              <el-button type="primary" @click="handleSearch" size="small" class="search-btn">
                搜索
              </el-button>
              <el-button @click="handleReset" size="small" class="reset-btn">
                重置
              </el-button>
            </div>

            <!-- 新增用户按钮 -->
            <div class="add-user-section">
              <el-button type="success" @click="handleAdd" :icon="Plus" size="small" class="add-dept-btn">
                新增用户
              </el-button>
            </div>
          </div>
</div>

        <!-- 用户列表 -->
        <div class="user-list">
          <div class="user-table-wrapper">
            <div class="user-table-scroll">
              <table class="user-table">
                <thead class="table-header">
                  <tr>
                    <th class="col-username">用户名</th>
                    <th class="col-realname">姓名</th>
                    <th class="col-gender">性别</th>
                    <th class="col-department">部门</th>
                    <th class="col-position">岗位</th>
                    <th class="col-role">角色</th>
                    <th class="col-status">状态</th>
                    <th class="col-email">邮箱</th>
                    <th class="col-join-date">入职时间</th>
                    <th class="col-leave-date">离职时间</th>
                    <th class="col-action">操作</th>
                  </tr>
                </thead>
                <tbody class="table-body" v-if="paginatedUsers.length > 0">
                  <tr
                    v-for="user in paginatedUsers"
                    :key="user.id"
                    class="table-row"
                  >
                    <td class="col-username">
                      <span>{{ user.username }}</span>
                    </td>
                    <td class="col-realname">
                      <div class="user-info">
                        <el-avatar :size="32" :src="user.avatar">
                          {{ user.realName.charAt(0) }}
                        </el-avatar>
                        <span class="user-name">{{ user.realName }}</span>
                      </div>
                    </td>
                    <td class="col-gender">
                      <el-tag :type="user.gender === '男' ? 'primary' : 'danger'" size="small">
                        {{ user.gender }}
                      </el-tag>
                    </td>
                    <td class="col-department">
                      <span>{{ getDepartmentName(user.departmentId) }}</span>
                    </td>
                    <td class="col-position">
                      <span>{{ user.position }}</span>
                    </td>
                    <td class="col-role">
                      <el-tag :type="getRoleTagType(user.role)" size="small">
                        {{ getRoleLabel(user.role) }}
                      </el-tag>
                    </td>
                    <td class="col-status">
                      <el-tag :type="getStatusTagType(user.status)" size="small">
                        {{ user.status === 'active' ? '在职' : '离职' }}
                      </el-tag>
                    </td>
                    <td class="col-email">
                      <span>{{ user.email }}</span>
                    </td>
                    <td class="col-join-date">
                      <span>{{ user.createTime }}</span>
                    </td>
                    <td class="col-leave-date">
                      <span>{{ user.leaveTime || '-' }}</span>
                    </td>
                    <td class="col-action">
                      <div class="action-buttons">
                        <el-button type="primary" size="small" plain @click="handleEdit(user)">
                          编辑
                        </el-button>
                        <el-button
                          :type="user.status === 'active' ? 'warning' : 'success'"
                          size="small"
                          plain
                          @click="handleToggleStatus(user)"
                        >
                          {{ user.status === 'active' ? '离职' : '入职' }}
                        </el-button>
                        <el-button type="danger" size="small" plain @click="handleDelete(user)">
                          删除
                        </el-button>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>

              <!-- 空状态 -->
              <div v-if="paginatedUsers.length === 0" class="empty-state">
                <el-empty :description="currentDepartment.id ? '该部门暂无用户' : '暂无用户数据'" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 - 右下角固定 -->
    <div class="pagination-fixed" v-if="filteredUsers.length > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="filteredUsers.length"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        small
      />
    </div>



    <!-- 用户弹窗组件 -->
    <UserDialog
      v-model:visible="dialogVisible"
      :title="dialogTitle"
      :form-data="formData"
      :departments="departmentTree"
      @submit="handleDialogSubmit"
      @cancel="resetForm"
    />

    <!-- 部门弹窗组件 -->
    <DepartmentDialog
      v-model:visible="departmentDialogVisible"
      :title="departmentDialogTitle"
      :form-data="departmentFormData"
      :departments="departmentTree"
      @submit="handleDepartmentDialogSubmit"
      @cancel="resetDepartmentForm"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, OfficeBuilding, User } from '@element-plus/icons-vue'
import UserDialog from './components/UserDialog.vue'
import DepartmentDialog from './components/DepartmentDialog.vue'

// 部门数据接口
interface Department {
  id: number
  name: string
  parentId?: number
  type: 'company' | 'department'
  userCount: number
  children?: Department[]
}

// 用户数据接口
interface UserData {
  id: number
  username: string
  nickname: string
  realName: string
  gender: '男' | '女'
  email: string
  phone?: string
  role: 'admin' | 'staff' | 'user'
  position: string
  status: 'active' | 'inactive'
  avatar?: string
  createTime: string
  leaveTime?: string
  lastLogin?: string
  departmentId: number
}

// 部门相关
const departmentTreeRef = ref()
const departmentSearchKeyword = ref('')
const currentDepartment = ref<Department>({ id: 0, name: '全部用户', type: 'company', userCount: 0 })

// 用户搜索和筛选
const userSearchKeyword = ref('')
const roleFilter = ref('')
const statusFilter = ref('')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)



// 树形组件配置
const treeProps = {
  children: 'children',
  label: 'name'
}

// 用户弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formData = ref<Partial<UserData>>({})

// 部门弹窗相关
const departmentDialogVisible = ref(false)
const departmentDialogTitle = ref('')
const departmentFormData = ref<Partial<Department>>({})

// 基础部门数据（不包含userCount，将动态计算）
const baseDepartmentTree = ref<Omit<Department, 'userCount'>[]>([
  {
    id: 1,
    name: '十一智库科技有限公司',
    type: 'company',
    children: [
      {
        id: 2,
        name: '技术部',
        parentId: 1,
        type: 'department',
        userCount: 0,
        children: [
          { id: 3, name: '前端组', parentId: 2, type: 'department', userCount: 0 },
          { id: 4, name: '后端组', parentId: 2, type: 'department', userCount: 0 },
          { id: 5, name: '测试组', parentId: 2, type: 'department', userCount: 0 }
        ]
      },
      {
        id: 6,
        name: '产品部',
        parentId: 1,
        type: 'department',
        userCount: 0,
        children: [
          { id: 7, name: '产品设计组', parentId: 6, type: 'department', userCount: 0 },
          { id: 8, name: 'UI设计组', parentId: 6, type: 'department', userCount: 0 }
        ]
      },
      {
        id: 9,
        name: '运营部',
        parentId: 1,
        type: 'department',
        userCount: 0
      }
    ]
  }
])

// 计算每个部门的用户数量
const calculateDepartmentUserCount = (departmentId: number): number => {
  // 如果是全部用户（departmentId为0），返回所有用户数量
  if (departmentId === 0) {
    return userData.value.length
  }

  const getAllDepartmentIds = (deptId: number): number[] => {
    const ids = [deptId]

    const findAllChildren = (nodes: any[], targetId: number) => {
      nodes.forEach(node => {
        if (node.id === targetId && node.children) {
          // 找到目标部门，添加所有子部门
          const addChildren = (children: any[]) => {
            children.forEach(child => {
              ids.push(child.id)
              if (child.children) {
                addChildren(child.children)
              }
            })
          }
          addChildren(node.children)
        }
        if (node.children) {
          findAllChildren(node.children, targetId)
        }
      })
    }

    findAllChildren(baseDepartmentTree.value, deptId)
    return ids
  }

  const departmentIds = getAllDepartmentIds(departmentId)
  const users = userData.value.filter(user => departmentIds.includes(user.departmentId))

  return users.length
}

// 动态计算用户数量的部门树
const departmentTree = computed(() => {
  const addUserCount = (nodes: any[]): Department[] => {
    return nodes.map(node => ({
      ...node,
      userCount: calculateDepartmentUserCount(node.id),
      children: node.children ? addUserCount(node.children) : undefined
    }))
  }
  return addUserCount(baseDepartmentTree.value)
})

// 模拟用户数据
const userData = ref<UserData[]>([
  {
    id: 1,
    username: 'admin',
    nickname: '系统管理员',
    realName: '管理员',
    gender: '男',
    email: 'admin@company.com',
    phone: '13800138000',
    role: 'admin',
    position: '系统管理员',
    status: 'active',
    departmentId: 9,
    createTime: '2024-01-15',
    lastLogin: '2024-12-09 14:30:00'
  },
  {
    id: 2,
    username: 'zhangsan',
    nickname: '张三',
    realName: '张三',
    gender: '男',
    email: 'zhangsan@company.com',
    phone: '13800138001',
    role: 'staff',
    position: '前端工程师',
    status: 'active',
    departmentId: 3,
    createTime: '2024-02-20',
    lastLogin: '2024-12-08 16:45:00'
  },
  {
    id: 3,
    username: 'lisi',
    nickname: '李四',
    realName: '李四',
    gender: '女',
    email: 'lisi@company.com',
    phone: '13800138002',
    role: 'user',
    position: '后端工程师',
    status: 'active',
    departmentId: 4,
    createTime: '2024-03-10',
    lastLogin: '2024-12-07 09:20:00'
  },
  {
    id: 4,
    username: 'wangwu',
    nickname: '王五',
    realName: '王五',
    gender: '男',
    email: 'wangwu@company.com',
    phone: '13800138003',
    role: 'user',
    position: '产品经理',
    status: 'inactive',
    departmentId: 7,
    createTime: '2024-04-05',
    leaveTime: '2024-11-30',
    lastLogin: '2024-11-30 13:15:00'
  },
  {
    id: 5,
    username: 'zhaoliu',
    nickname: '赵六',
    realName: '赵六',
    gender: '女',
    email: 'zhaoliu@company.com',
    phone: '13800138004',
    role: 'staff',
    position: '运营专员',
    status: 'active',
    departmentId: 9,
    createTime: '2024-05-12',
    lastLogin: '2024-12-06 11:30:00'
  }
])

// 过滤部门树
const filteredDepartmentTree = computed(() => {
  if (!departmentSearchKeyword.value) {
    return departmentTree.value
  }

  const filterTree = (nodes: Department[]): Department[] => {
    return nodes.filter(node => {
      const matchName = node.name.toLowerCase().includes(departmentSearchKeyword.value.toLowerCase())
      const hasMatchingChildren = node.children && filterTree(node.children).length > 0

      if (matchName || hasMatchingChildren) {
        return {
          ...node,
          children: node.children ? filterTree(node.children) : undefined
        }
      }
      return false
    }).map(node => ({
      ...node,
      children: node.children ? filterTree(node.children) : undefined
    }))
  }

  return filterTree(departmentTree.value)
})

// 获取部门下的所有用户（包括子部门）
const getDepartmentUsers = (departmentId: number): UserData[] => {
  if (departmentId === 0) {
    return userData.value // 返回所有用户
  }

  const getAllDepartmentIds = (deptId: number): number[] => {
    const ids = [deptId]

    const findAllChildren = (nodes: any[], targetId: number) => {
      nodes.forEach(node => {
        if (node.id === targetId && node.children) {
          // 找到目标部门，添加所有子部门
          const addChildren = (children: any[]) => {
            children.forEach(child => {
              ids.push(child.id)
              if (child.children) {
                addChildren(child.children)
              }
            })
          }
          addChildren(node.children)
        }
        if (node.children) {
          findAllChildren(node.children, targetId)
        }
      })
    }

    findAllChildren(baseDepartmentTree.value, deptId)
    return ids
  }

  const departmentIds = getAllDepartmentIds(departmentId)
  return userData.value.filter(user => departmentIds.includes(user.departmentId))
}

// 过滤后的用户数据
const filteredUsers = computed(() => {
  let users = getDepartmentUsers(currentDepartment.value.id)

  // 应用搜索和筛选
  return users.filter(user => {
    const matchSearch = !userSearchKeyword.value ||
      user.nickname.toLowerCase().includes(userSearchKeyword.value.toLowerCase()) ||
      user.email.toLowerCase().includes(userSearchKeyword.value.toLowerCase())
    const matchRole = !roleFilter.value || user.role === roleFilter.value
    const matchStatus = !statusFilter.value || user.status === statusFilter.value

    return matchSearch && matchRole && matchStatus
  })
})

// 分页后的用户数据
const paginatedUsers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredUsers.value.slice(start, end)
})



// 获取角色标签类型
const getRoleTagType = (role: string) => {
  switch (role) {
    case 'admin': return 'danger'
    case 'staff': return 'warning'
    case 'user': return 'info'
    default: return 'info'
  }
}

// 获取角色标签文本
const getRoleLabel = (role: string) => {
  switch (role) {
    case 'admin': return '管理员'
    case 'staff': return '后台人员'
    case 'user': return '普通用户'
    default: return '未知'
  }
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  return status === 'active' ? 'success' : 'danger'
}

// 获取部门名称
const getDepartmentName = (departmentId: number): string => {
  const findDepartment = (depts: any[], id: number): any | null => {
    for (const dept of depts) {
      if (dept.id === id) return dept
      if (dept.children) {
        const found = findDepartment(dept.children, id)
        if (found) return found
      }
    }
    return null
  }

  const dept = findDepartment(baseDepartmentTree.value, departmentId)
  return dept ? dept.name : '未知部门'
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  ElMessage.success('搜索完成')
}

// 重置搜索
const handleReset = () => {
  userSearchKeyword.value = ''
  roleFilter.value = ''
  statusFilter.value = ''
  currentPage.value = 1
  ElMessage.info('已重置搜索条件')
}

// 部门点击处理
const handleDepartmentClick = (department: Department) => {
  currentDepartment.value = department
  currentPage.value = 1
  ElMessage.info(`已切换到：${department.name}`)
}

// 部门右键菜单
const handleDepartmentRightClick = (event: MouseEvent, data: any) => {
  // 可以在这里添加右键菜单功能
  console.log('右键点击部门:', data)
}

// 新增部门
const handleAddDepartment = () => {
  departmentDialogTitle.value = '新增部门'
  departmentFormData.value = {
    name: '',
    parentId: currentDepartment.value.id || undefined,
    type: 'department'
  }
  departmentDialogVisible.value = true
}

// 新增用户
const handleAdd = () => {
  dialogTitle.value = '新增用户'
  formData.value = {
    username: '',
    nickname: '',
    email: '',
    role: 'user',
    status: 'active',
    departmentId: currentDepartment.value.id || 1
  }
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (user: UserData) => {
  dialogTitle.value = '编辑用户'
  formData.value = { ...user }
  dialogVisible.value = true
}

// 切换用户状态
const handleToggleStatus = async (user: UserData) => {
  const action = user.status === 'active' ? '禁用' : '启用'
  try {
    await ElMessageBox.confirm(
      `确定要${action}用户 "${user.nickname}" 吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    user.status = user.status === 'active' ? 'inactive' : 'active'
    ElMessage.success(`用户 "${user.nickname}" 已${action}`)
  } catch {
    ElMessage.info('已取消操作')
  }
}

// 删除用户
const handleDelete = async (user: UserData) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${user.nickname}" 吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const index = userData.value.findIndex(u => u.id === user.id)
    if (index > -1) {
      userData.value.splice(index, 1)
      ElMessage.success(`用户 "${user.nickname}" 已删除`)
    }
  } catch {
    ElMessage.info('已取消删除')
  }
}



// 用户弹窗提交
const handleDialogSubmit = (data: Partial<UserData>) => {
  if (data.id) {
    // 编辑
    const index = userData.value.findIndex(u => u.id === data.id)
    if (index > -1) {
      userData.value[index] = { ...userData.value[index], ...data }
      ElMessage.success('用户信息已更新')
    }
  } else {
    // 新增
    const newUser: UserData = {
      id: Date.now(),
      username: data.username!,
      nickname: data.nickname!,
      realName: data.realName || data.nickname!,
      gender: data.gender || '男',
      email: data.email!,
      role: data.role!,
      status: data.status!,
      departmentId: data.departmentId!,
      position: data.position || '员工',
      createTime: new Date().toLocaleString('zh-CN')
    }
    userData.value.unshift(newUser)
    ElMessage.success('用户已添加')
  }

  dialogVisible.value = false
  resetForm()
}

// 部门弹窗提交
const handleDepartmentDialogSubmit = (data: Partial<Department>) => {
  if (data.id) {
    // 编辑部门
    ElMessage.success('部门信息已更新')
  } else {
    // 新增部门
    const newDepartment: Department = {
      id: Date.now(),
      name: data.name!,
      parentId: data.parentId,
      type: data.type!,
      userCount: 0
    }

    // 这里应该添加到对应的父部门下，简化处理
    ElMessage.success('部门已添加')
  }

  departmentDialogVisible.value = false
  resetDepartmentForm()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
}

// 重置用户表单
const resetForm = () => {
  formData.value = {}
}

// 重置部门表单
const resetDepartmentForm = () => {
  departmentFormData.value = {}
}

onMounted(() => {
  // 组件挂载时的初始化逻辑
  // 默认展开第一级部门
  nextTick(() => {
    if (departmentTreeRef.value) {
      try {
        // 使用正确的方法展开节点
        if (typeof departmentTreeRef.value.setExpandedKeys === 'function') {
          departmentTreeRef.value.setExpandedKeys([1])
        } else {
          // 如果setExpandedKeys方法不存在，使用其他方式展开
          console.warn('setExpandedKeys方法不存在，跳过自动展开')
        }
      } catch (error) {
        console.warn('展开部门树失败:', error)
      }
    }
  })
})
</script>

<style scoped>
.user-management {
  padding: 24px;
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
}

/* 顶部工具栏 */
.top-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 16px;
}

.toolbar-left {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.page-subtitle {
  font-size: 14px;
  color: #6b7280;
}

.toolbar-right {
  display: flex;
  gap: 12px;
}

/* 主要内容区域 */
.main-content {
  flex: 1;
  display: flex;
  gap: 24px;
  min-height: 0;
}

.form-row {
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
}

.form-item-inline {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 200px;
}

.form-item-inline label {
  font-size: 14px;
  font-weight: 600;
  color: #475569;
  white-space: nowrap;
  min-width: 60px;
}

.form-item-inline .el-input,
.form-item-inline .el-select {
  width: 160px;
}

.button-group {
  display: flex;
  gap: 12px;
  margin-left: auto;
}

.search-btn {
  background: linear-gradient(90deg, rgb(91, 124, 255) 0%, rgb(166, 133, 255) 100%);
  border: none;
  border-radius: 8px;
  padding: 8px 20px;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.search-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.reset-btn {
  background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
  border: 1px solid #cbd5e1;
  color: #64748b;
  border-radius: 8px;
  padding: 8px 20px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.reset-btn:hover {
  background: linear-gradient(135deg, #e2e8f0 0%, #cbd5e1 100%);
  transform: translateY(-1px);
}

.add-btn {
   background: linear-gradient(90deg, rgb(91, 124, 255) 0%, rgb(166, 133, 255) 100%);
  border: none;
  border-radius: 8px;
  padding: 8px 20px;
  font-weight: 600;
 box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.add-btn:hover {
  transform: translateY(-1px);
   box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

/* 部门面板 */
.department-panel {
  width: 300px;
  background: white;
  border-radius: 12px;
  border: 1px solid #e5e7eb;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.panel-header {
  padding: 20px;
  border-bottom: 1px solid #e5e7eb;
  background: linear-gradient(135deg, #f8faff 0%, #f0f4ff 100%);
}

.header-title-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.add-dept-btn {
  background: linear-gradient(90deg, rgb(91, 124, 255) 0%, rgb(166, 133, 255) 100%);
  border: none;
  border-radius: 6px;
  font-weight: 500;
  box-shadow: 0 2px 6px rgba(91, 124, 255, 0.3);
  transition: all 0.2s ease;
}

.add-dept-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 10px rgba(91, 124, 255, 0.4);
}

.search-box {
  margin-bottom: 0;
}

.department-tree {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.tree-node {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.node-icon {
  color: #6b7280;
  font-size: 16px;
}

.node-label {
  flex: 1;
  font-size: 14px;
  color: #374151;
}

.user-count {
  font-size: 12px;
  color: #9ca3af;
}

/* 用户面板 */
.user-panel {
  flex: 1;
  background: white;
  border-radius: 12px;
  border: 1px solid #e5e7eb;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.user-panel .panel-header {
  padding: 20px;
  border-bottom: 1px solid #e5e7eb;
  background: linear-gradient(135deg, #f8faff 0%, #f0f4ff 100%);
}

/* 搜索区域布局 */
.search-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.search-filters {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

.add-user-section {
  display: flex;
}

/* 按钮样式 */
.search-btn {
  background: linear-gradient(90deg, rgb(91, 124, 255) 0%, rgb(166, 133, 255) 100%);
  border: none;
  border-radius: 6px;
  font-weight: 500;
  box-shadow: 0 2px 6px rgba(91, 124, 255, 0.3);
  transition: all 0.2s ease;
}

.search-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 10px rgba(91, 124, 255, 0.4);
}

.reset-btn {
  background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
  border: 1px solid #cbd5e1;
  color: #64748b;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.2s ease;
}

.reset-btn:hover {
  background: linear-gradient(135deg, #e2e8f0 0%, #cbd5e1 100%);
  transform: translateY(-1px);
}

.add-user-btn {
  background: linear-gradient(90deg, rgb(34, 197, 94) 0%, rgb(16, 185, 129) 100%);
  border: none;
  border-radius: 6px;
  font-weight: 500;
  box-shadow: 0 2px 6px rgba(34, 197, 94, 0.3);
  transition: all 0.2s ease;
}

.add-user-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 10px rgba(34, 197, 94, 0.4);
}

/* 用户列表 */
.user-list {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding: 20px;
}

/* 表格包装器 */
.user-table-wrapper {
  flex: 1;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #e5e7eb;
  overflow: hidden;
}

/* 表格滚动容器 */
.user-table-scroll {
  width: 100%;
  height: 100%;
  overflow: auto;
}

/* 滚动条样式 */
.user-table-scroll::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.user-table-scroll::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 3px;
}

.user-table-scroll::-webkit-scrollbar-thumb {
  background: #d1d5db;
  border-radius: 3px;
}

.user-table-scroll::-webkit-scrollbar-thumb:hover {
  background: #9ca3af;
}

.user-table-scroll::-webkit-scrollbar-corner {
  background: #f1f5f9;
}

/* 表格样式 */
.user-table {
  width: 100%;
  border-collapse: collapse;
  background: white;
  min-width: 1400px;
  table-layout: fixed;
}

/* 表头样式 */
.table-header {
background: linear-gradient(135deg, #e0e7ff 0%, #f3e8ff 100%);
  border-bottom: 1px solid #c7d2fe;
  color: #4338ca;
  font-size: 16px;  position: sticky;
  top: 0;
  z-index: 10;
}

.table-header th {
  padding: 16px 12px;
  text-align: left;
  font-weight: 600;
  font-size: 14px;
  white-space: nowrap;
}

.table-header th:last-child {
  border-right: none;
}

/* 表格主体 */
.table-body tr {
  transition: background-color 0.2s;
}

.table-body tr:hover {
  background: #f8fafc;
}

.table-body tr:last-child {
  border-bottom: none;
}

.table-body td {
  padding: 16px 12px;
  vertical-align: middle;
  white-space: nowrap;
}

.table-body td:last-child {
  border-right: none;
}

/* 列宽定义 */
.col-username { width: 120px; }
.col-realname { width: 140px; }
.col-gender { width: 80px; }
.col-department { width: 120px; }
.col-position { width: 120px; }
.col-role { width: 100px; }
.col-status { width: 80px; }
.col-email { width: 180px; }
.col-join-date { width: 120px; }
.col-leave-date { width: 120px; }
.col-action {
  width: 220px !important;
  position: sticky;
  right: 0;
  background: inherit;
  z-index: 5;
}

/* 操作列固定样式 */
.table-header .col-action {
 background: linear-gradient(135deg, #e0e7ff 0%, #f3e8ff 100%);
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1);
}

.table-body .col-action {
  background: white;
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1);
}

.table-body tr:hover .col-action {
  background: #f8fafc;
}

/* 用户信息样式 */
.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-name {
  font-weight: 500;
  color: #1e293b;
  font-size: 14px;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: center;
}

.action-buttons .el-button {
  padding: 6px 16px;
  font-size: 12px;
  border-radius: 6px;
  white-space: nowrap;
}

/* 空状态样式 */
.empty-state {
  padding: 60px 20px;
  text-align: center;
  background: white;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 300px;
}

/* 分页样式 - 右下角固定，与部门管理完全一致 */
.pagination-fixed {
  position: fixed;
  bottom: 24px;
  right: 24px;
  z-index: 100;
  background: white;
  padding: 12px 16px;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  border: 1px solid #e5e7eb;
}

.pagination-fixed :deep(.el-pagination) {
  margin: 0;
}

.pagination-fixed :deep(.el-pagination .el-pager li) {
  background: transparent;
  border-radius: 6px;
  margin: 0 2px;
  transition: all 0.2s;
}

.pagination-fixed :deep(.el-pagination .el-pager li:hover) {
  background: #f3f4f6;
}

.pagination-fixed :deep(.el-pagination .el-pager li.is-active) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.pagination-fixed :deep(.el-pagination .btn-prev),
.pagination-fixed :deep(.el-pagination .btn-next) {
  border-radius: 6px;
  transition: all 0.2s;
}

.pagination-fixed :deep(.el-pagination .btn-prev:hover),
.pagination-fixed :deep(.el-pagination .btn-next:hover) {
  background: #f3f4f6;
}













/* 用户信息样式 */
.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-name {
  font-weight: 500;
  color: #1e293b;
  font-size: 14px;
}



/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.action-buttons .el-button {
  padding: 4px 12px;
  font-size: 12px;
  border-radius: 6px;
}

/* 空状态样式 */
.empty-state {
  padding: 60px 20px;
  text-align: center;
  background: white;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 300px;
}



/* 响应式设计 */
@media (max-width: 768px) {
  .user-management {
    padding: 16px;
  }

  .form-row {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }

  .form-item-inline {
    min-width: auto;
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .form-item-inline label {
    min-width: auto;
  }

  .form-item-inline .el-input,
  .form-item-inline .el-select {
    width: 100%;
  }

  .button-group {
    margin-left: 0;
    flex-direction: column;
    gap: 8px;
  }

  .search-btn,
  .reset-btn,
  .add-btn {
    width: 100%;
  }

  .list-header,
  .list-row {
    padding: 12px 16px;
  }

  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }
}

@media (max-width: 1024px) {
  .form-row {
    gap: 16px;
  }

  .form-item-inline {
    min-width: 180px;
  }

  .form-item-inline .el-input,
  .form-item-inline .el-select {
    width: 140px;
  }

  .button-group {
    flex-wrap: wrap;
  }
}

/* 标签样式优化 */
:deep(.el-tag) {
  border-radius: 6px;
  font-weight: 500;
}

/* 头像样式 */
:deep(.el-avatar) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-weight: 600;
}
</style>